package com.xxx.springboot.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * ③Shiro权限管理
 */
@Controller
@RequestMapping("")
public class ShiroController {

    /*
     * 首页
     */
    @RequestMapping("/")
    public String toIndexPage(Model model) {
        model.addAttribute("key","Shiro安全框架");
        return "index";
    }

    /*
     * 跳转到添加用户页面
     */
    @RequestMapping("/user/add")
    public String toAddPage() {
        return "/user/add";
    }

    /*
     * 跳转到编辑用户页面
     */
    @RequestMapping("/user/edit")
    public String toEditPage() {
        return "/user/edit";
    }

    /*
     * 跳转到登录页面
     */
    @RequestMapping("/toLogin")
    public String toLoginPage() {
        return "login";
    }

    /*
     * 登录校验
     */
    @RequestMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username,
                          @RequestParam("password") String password,
                          Model model) {
        // 获取当前用户
        Subject currentUser = SecurityUtils.getSubject();
        // 如果当前用户未进行认证
        if(!currentUser.isAuthenticated()) {
            // 将用户名和密码加密封装为token
            UsernamePasswordToken token = new UsernamePasswordToken(username, password);
            try {
                // 执行登录
                currentUser.login(token);
            } catch (UnknownAccountException uae) { // 用户名不存在
                model.addAttribute("errorMsg","用户名不存在！");
                return "login";
            } catch (IncorrectCredentialsException ice) { // 密码错误
                model.addAttribute("errorMsg", "密码错误！");
                return "login";
            }
        }
        return "index";
    }

}
